package com.teambsc4.todo.viewmodel

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.location.LocationManager
import android.net.Uri
import android.provider.MediaStore
import android.util.Base64
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.TimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.core.app.ActivityCompat.startActivityForResult
import androidx.core.content.ContextCompat.getSystemService
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.teambsc4.todo.App
import com.teambsc4.todo.entities.TaskItem
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter


class MainPageViewModel() : ViewModel() {

    //Add button status
    fun isConfirmEnabled(): Boolean {
        return taskTitle.isNotBlank() &&
            taskDescription.isNotBlank() &&
            taskEndTime.isNotBlank() &&
            taskPriority.isNotBlank() &&
            taskState.isNotBlank()
    }


    var id: Int = 1
    var isDropdownExpanded by mutableStateOf(false)
    var isDropdownExpanded2 by mutableStateOf(false)

    // MutableState Used for bidirectional data binding
    var taskTitle by mutableStateOf("")//title
    var taskDescription by mutableStateOf("")//Description
    var taskPriority by mutableStateOf("")//priority
    var taskEndTime by mutableStateOf("")//end time
    var imageUri: Uri? by mutableStateOf(null)//Image
    var taskState by mutableStateOf("")//state
    var taskGps: String by mutableStateOf("")//GPS
    var tasks by mutableStateOf<List<TaskItem>>(emptyList())//tasksList

    init {
        viewModelScope.launch { tasks = App.Dao.taskItemDao.queryAll() }
    }

    // Clear input box data
    fun clearInputFields() {
        taskTitle = ""
        taskDescription = ""
        taskPriority = ""
        taskEndTime = ""
        taskState = ""
        taskGps = ""
        imageUri = null
        id = 0
    }

    //Current entry data
    fun currentItem(taskId: Int) {
        val item = App.Dao.taskItemDao.queryById(taskId)
        taskTitle = item.title
        taskDescription = item.description
        taskPriority = item.priority.toString()
        taskEndTime = item.endTime
        imageUri = Uri.parse(item.image)
        taskState = item.status
        taskGps = item.gps
        id = item.id.toInt()
    }

    // Function to update the value of the title
    fun updateTitle(newTitle: String) {
        taskTitle = newTitle
        Log.e("TAG", "updateTitle:$taskTitle ")
    }

    //Function to update the value of the content
    fun updateDescription(newDescription: String) {
        taskDescription = newDescription
        Log.e("TAG", "updateTitle:$taskDescription ")

    }

    //Function to update the value of the end time
    fun updateEndTime(it: String) {
        val validatedInput = it.takeIf { input ->
            input.isEmpty() || (input.length in 1..3)
        } ?: taskEndTime // The hypothesis is a variable that was defined earlier
        taskEndTime = validatedInput // The hypothesis is also a variable that was defined earlier
        Log.e("TAG", "updateTitle:$taskEndTime ")

    }

    //Function to update the value of the priority
    fun updatePriority(it: String) {
        taskPriority = it
        Log.e("TAG", "updateTitle:$taskPriority ")

    }

    //Function to update the value of the image
    fun updateImage(it: Uri) {
        imageUri = it
        Log.e("TAG", "updateTitle:${imageUri.toString()} ")

    }

    //update status
    fun updateStatus(it: String) {
        taskState = it
        Log.e("TAG", "updateTitle:$taskState ")

    }

    //update GPS
    fun updateGPS(it: String) {
        taskGps = it
        Log.e("TAG", "updateTitle:$taskGps ")
    }

    // Gets the current date and time
    fun getNowTime(): String {
        val currentDateTime = LocalDateTime.now()
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        return currentDateTime.format(formatter)
    }

    // Gets the current date and time
    fun getEndTime(daysToAdd: String): String {
        val days = daysToAdd.toLongOrNull()
        val currentDateTime = LocalDateTime.now()
        val futureDateTime = currentDateTime.plusDays(days!!)
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        return futureDateTime.format(formatter)
    }


    fun getEndTime2(daysToSubtract: String): String {
        val days = daysToSubtract.toLongOrNull()
        val currentDateTime = LocalDateTime.now()
        val pastDateTime = currentDateTime.minusDays(days ?: 0)
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        return pastDateTime.format(formatter)
    }


    //Add button click event
    fun confirmTaskButton() {
        App.Dao.taskItemDao.insertTask(
            TaskItem(
                title = taskTitle,
                description = taskDescription,
                priority = taskPriority,
                image = imageUri.toString(),//图片
                beginTime = getNowTime(),
                endTime = taskEndTime,
                status = taskState,
                gps = taskGps,
            )
        )
        tasks = App.Dao.taskItemDao.queryAll()
        Log.e(
            "TAG", "confirmTaskButton: " +
                "taskTitle" + taskTitle +
                "taskDescription" + taskDescription +
                "taskPriority" + taskPriority +
                " imageUri.toString()" + imageUri.toString() +
                "taskEndTime" + taskEndTime + "" +
                "taskState" + taskState
        )
    }

    // Delete button here for the task
    fun onDeleteTaskButton(item: TaskItem) {
        viewModelScope.launch {
            App.Dao.taskItemDao.deleteTask(item)
            tasks = App.Dao.taskItemDao.queryAll()
        }
    }

    //change
    fun upDateTask() {
        App.Dao.taskItemDao.apply {
            deleteById(id)
            insertTask(
                TaskItem(
                    id = id,
                    title = taskTitle,
                    description = taskDescription,
                    priority = taskPriority,
                    image = imageUri.toString(),//图片
                    beginTime = getNowTime(),
                    endTime = taskEndTime,
                    status = taskState,
                    gps = taskGps,
                )
            )
        }
        tasks = App.Dao.taskItemDao.queryAll()
    }

}